import { debounce } from "lodash";
import { useRef, useState, useEffect } from "react";

export function useSizeObserver<E extends HTMLElement = HTMLElement>() {
  const ref_list = useRef<E | null>(null);
  const [width, set_width] = useState<number>(0);
  const [height, set_height] = useState<number>(0);
  useEffect(() => {
    const ele = ref_list.current;
    if (!ele) return;
    const on_resize = debounce(() => {
      const { width, height } = ele.getBoundingClientRect();
      set_width(width);
      set_height(height);
    });
    const resize_ob = new ResizeObserver(on_resize);
    resize_ob.observe(ele);
    on_resize();
    return () => resize_ob.disconnect();
  }, []);
  return [ref_list, width, height] as const;
}
